<?php

namespace Plu\qdh\Services;

use Httpful\Request;
use Plu\qdh\Models\App\QrCode;
use Plu\qdh\Services\FileService;
use Plu\qdh\Services\ServiceBase;


class QrService extends ServiceBase {

    private $_accessToken;

    private $_errCode;

    const ACCESS_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s";
    
    const QR_URL = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=%s";

    public function changeQrName($changeId, $name) {
        $model = QrCode::findFirst($changeId);
        if ($model) {
            $model->name = $name;
            if ($model->save()) {
                return true;
            }
        }
        return false;
    }

    public function getAllQr() {
        $items = QrCode::getAllItems();
        return $items;
    }

    public function getQrList($limit, $offset) {
        list($count, $items) = QrCode::getItems($limit, $offset);
        return [$count, $items];
    }

    // 创建小程序分销二维码
    public function createQrDistribution($shopName) {

        $isExis = QrCode::getItemByShopName($shopName);

        if ($isExis) {
            return [
                'code' => -2,
                'msg'  => '分销名已存在'
            ];
        }

        $prefix = 0;

        $num = QrCode::maximum([
            'column' => 'id'
        ]) + 1;

        if ($num == 1) {
            $prefix = 1000;
        }

        $createId = $prefix + $num;

        $createUrl = $this->createQrUrl($createId);

        if ($this->getErrorCode() == 0) {

            $model = new QrCode;

            $model->id     = $createId;
            $model->name   = $shopName;
            $model->imgUrl = $createUrl;
            $model->createTime = date('Y-m-d H:i:s', time());
            $model->save();

            return [
                'code' => 1,
                'msg'  => '成功创建二维码'
            ];

        }

        return [
            'code' => 0,
            'msg'  => '二维码创建失败'
        ];

    }

    public function getErrorCode() {
        return $this->_errCode;
    }

    // 生成小程序二维码
    public function createQrUrl($createId) {

        $this->makeAccessToken();

        if (!$this->_accessToken) {
            $this->_errCode = -1;
        }

        $payLoad =  [
            'scene' => 'custId='.$createId,
            'page'  => 'pages/project',
            'width' => 430,
            'auto_color' => true
        ];

        $payLoad    = json_encode($payLoad);
        $requestUrl = sprintf(self::QR_URL, $this->_accessToken);
        $request    = Request::post($requestUrl, $payLoad)->send();
        $body       = $request->body;
        $fileName   = 'QrCode'.rand(0,999).time().'.png';
        $filePath   = APP_CACHE_PATH.'/'.$fileName;

        file_put_contents($filePath, $body);

        $fileService = new FileService;
        $assUrl      = $fileService->uploadFile($filePath, $fileName);
        $this->_errCode = 0;
        return $assUrl;

    }


    private function makeAccessToken() {
        $requestUrl  = sprintf(self::ACCESS_TOKEN_URL, \Wechat::APPID, \Wechat::SECRET_KEY);
        $response    = Request::get($requestUrl)->send();
        $body        = $response->body;
        $accessToken = $body->access_token;
        $this->_accessToken = $accessToken;
    }





}